<template>
  <el-popover v-model:visible="visible" placement="bottom" :width="300" trigger="click" :disabled="disabled">
    <template #reference>
      <div class="el-select" @mouseenter="isHover = true" @mouseleave="isHover = false">
        <div class="el-select__wrapper" :class="{ 'is-focused': visible, 'is-hovering': isHover }">
          <div v-if="defaultCheckedList.length" class="el-select__selected-item el-select__input-wrapper">
            {{defaultCheckedList.map(v => v.name).join(', ')}}
          </div>
          <div v-else class="el-select__selection">
            <div class="el-select__selected-item el-select__placeholder is-transparent">{{ _title }}</div>
          </div>
          <div class="el-select__suffix">
            <el-icons v-if="isHover && defaultCheckedList.length" class="el-select__caret el-select__icon"
              name="CircleClose" @click.stop="onClear" />
            <el-icons v-else class="el-select__caret el-select__icon" :class="{ 'is-reverse': visible }"
              name="ArrowDown" />
          </div>
        </div>
      </div>
    </template>
    <Organization ref="selectRef" :isDep="type === 'department'" :defaultCheckedList="defaultCheckedList"
      :rootNode="rootNode" :multiple="multiple" @change="onSelectChange" plain />
  </el-popover>
</template>

<script setup>
import { ref, computed } from 'vue';
import Organization from './Organization.vue';

const props = defineProps({
  // 选择类型：员工 or 部门
  type: {
    type: String,
    default: 'user',
    validator: (value) => {
      return ['user', 'department'].includes(value);
    },
  },
  isObject: Boolean,
  placeholder: String,
  // 是否多选
  multiple: Boolean,
  disabled: Boolean,
  rootNode: Object,
});
const emit = defineEmits(['change']);

const visible = ref(false);
const modelValue = defineModel({
  type: [Object, Array, Number],
});

const isHover = ref(false);

const _title = computed(() => {
  return props.placeholder || (props.type === 'user' ? '选择员工' : '选择部门');
});

const selectRef = ref(null);
const onSelectChange = () => {
  if (!props.multiple) { // 如果是单选，直接关闭弹窗
    onConfirm();
  }
  emit('change', modelValue.value)
};
const onConfirm = () => {
  const selected = selectRef.value.getCheckedList();
  setMap(selected)
  const key = props.type === 'user' ? 'user_id' : 'department_id';
  const values = props.isObject ? selected : selected.map(v => v[key]);
  modelValue.value = props.multiple ? values : values[0];
  visible.value = false;
};
const onClear = () => {
  modelValue.value = props.multiple ? [] : null;
  visible.value = false;
  selectRef.value.setCheckedList([]);
  emit('change', modelValue.value);
};

const defaultCheckedList = computed(() => {
  const key = props.type === 'user' ? 'user_id' : 'department_id';
  if (props.multiple) {
    return (modelValue.value || []).map(v => {
      return props.isObject ? v : { [key]: v, name: getMap[v] };
    });
  } else {
    return modelValue.value ? [props.isObject ? modelValue.value : { [key]: modelValue.value, name: getMap(modelValue.value) }] : [];
  }
});


const cacheMap = {};
const setMap = (arr) => {
  arr.forEach(v => {
    const key = props.type === 'user' ? 'user_id' : 'department_id';
    cacheMap[`${key}_${v[key]}`] = v;
  })
};
const getMap = (id) => {
  const key = props.type === 'user' ? 'user_id' : 'department_id';
  return cacheMap[`${key}_${id}`]?.name || id;
};
</script>